// 生产记录页面JavaScript
class ProductionRecordsApp {
    constructor() {
        this.baseURL = '';
        this.currentPage = 1;
        this.pageSize = 10;
        this.totalPages = 0;
        this.totalItems = 0;
        this.currentRecords = [];
        this.selectedRecords = new Set();
        this.currentFilters = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.updateCurrentTime();
        this.loadProductionRecords();
        this.loadWorkOrders(); // Load work orders for dropdowns
        this.loadOperators(); // Load operators for dropdown
        
        // Update time every second
        setInterval(() => this.updateCurrentTime(), 1000);
        
        // Refresh realtime status every 30 seconds
        setInterval(() => this.refreshRealtimeStatus(), 30000);
    }

    bindEvents() {
        // Search event
        const searchInput = document.getElementById('recordSearch');
        if (searchInput) {
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.searchRecords();
                }
            });
        }

        // Filter events
        const recordTypeFilter = document.getElementById('recordTypeFilter');
        if (recordTypeFilter) {
            recordTypeFilter.addEventListener('change', () => this.applyFilters());
        }

        const workstationFilter = document.getElementById('workstationFilter');
        if (workstationFilter) {
            workstationFilter.addEventListener('change', () => this.applyFilters());
        }

        const shiftFilter = document.getElementById('shiftFilter');
        if (shiftFilter) {
            shiftFilter.addEventListener('change', () => this.applyFilters());
        }

        // Form submit events
        const productionForm = document.getElementById('productionForm');
        if (productionForm) {
            productionForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.addProductionRecord(new FormData(e.target));
            });
        }

        const rejectionForm = document.getElementById('rejectionForm');
        if (rejectionForm) {
            rejectionForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.addRejectionRecord(new FormData(e.target));
            });
        }

        const timeRangeForm = document.getElementById('timeRangeForm');
        if (timeRangeForm) {
            timeRangeForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.queryByTimeRange(new FormData(e.target));
            });
        }
    }

    updateCurrentTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN');
        const timeElement = document.getElementById('currentTime');
        if (timeElement) {
            timeElement.textContent = timeString;
        }
    }

    // API call function
    async apiCall(endpoint, options = {}) {
        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, {
                headers: { 'Content-Type': 'application/json', ...options.headers },
                ...options
            });
            
            const data = await response.json();
            if (!response.ok) throw new Error(data.message || `HTTP error! status: ${response.status}`);
            return data;
        } catch (error) {
            console.error('API call failed:', error);
            this.showToast(`Request failed: ${error.message}`, 'error');
            throw error;
        }
    }

    // Load production records
    async loadProductionRecords() {
        try {
            const response = await this.apiCall('/api/production-records');
            this.currentRecords = response.data || [];
            this.totalItems = this.currentRecords.length;
            this.totalPages = Math.ceil(this.totalItems / this.pageSize);
            
            this.renderProductionRecordsTable();
            this.updatePagination();
            this.updateStatistics();
        } catch (error) {
            console.error('Failed to load production records:', error);
            document.getElementById('productionRecordsTableBody').innerHTML = 
                '<tr><td colspan="11" class="error">Failed to load production record data</td></tr>';
        }
    }

    // Load work orders for dropdown
    async loadWorkOrders() {
        try {
            const response = await this.apiCall('/api/workorders');
            const workOrders = response.data || [];
            
            // Filter in-progress work orders
            const inProgressOrders = workOrders.filter(order => order.status === 'IN_PROGRESS');
            
            // Update production form dropdown
            const productionSelect = document.querySelector('#productionForm select[name="workOrderId"]');
            if (productionSelect) {
                productionSelect.innerHTML = '<option value="">Select work order in progress</option>' +
                    inProgressOrders.map(order => 
                        `<option value="${order.id}">${order.orderCode} - ${order.product?.productName || 'Unknown Product'}</option>`
                    ).join('');
            }

            // Update rejection form dropdown
            const rejectionSelect = document.querySelector('#rejectionForm select[name="workOrderId"]');
            if (rejectionSelect) {
                rejectionSelect.innerHTML = '<option value="">Select work order in progress</option>' +
                    inProgressOrders.map(order => 
                        `<option value="${order.id}">${order.orderCode} - ${order.product?.productName || 'Unknown Product'}</option>`
                    ).join('');
            }
        } catch (error) {
            console.error('Failed to load work orders:', error);
        }
    }

    // Load operators for dropdown
    async loadOperators() {
        try {
            const response = await this.apiCall('/api/production-records');
            const records = response.data || [];
            
            // Extract unique operators
            const operators = [...new Set(records.map(r => r.operator).filter(o => o))];
            
            const operatorFilter = document.getElementById('operatorFilter');
            if (operatorFilter) {
                operatorFilter.innerHTML = '<option value="">All Operators</option>' +
                    operators.map(op => `<option value="${op}">${op}</option>`).join('');
            }
        } catch (error) {
            console.error('Failed to load operators:', error);
        }
    }

    // Render production records table
    renderProductionRecordsTable() {
        const tbody = document.getElementById('productionRecordsTableBody');
        
        if (this.currentRecords.length === 0) {
            tbody.innerHTML = '<tr><td colspan="11" class="no-data">No production record data</td></tr>';
            return;
        }

        // Pagination
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        const pageRecords = this.currentRecords.slice(startIndex, endIndex);

        const rows = pageRecords.map(record => {
            const isSelected = this.selectedRecords.has(record.id);
            const typeBadge = this.getRecordTypeBadge(record.recordType);
            
            return `
                <tr ${isSelected ? 'class="selected"' : ''}>
                    <td>
                        <input type="checkbox" value="${record.id}" 
                               ${isSelected ? 'checked' : ''} 
                               onchange="app.toggleRecordSelection(${record.id})">
                    </td>
                    <td>
                        <a href="#" onclick="app.showRecordDetail(${record.id})" class="record-link">
                            ${record.workOrder?.orderCode || '-'}
                        </a>
                    </td>
                    <td>${record.quantity || 0}</td>
                    <td>${typeBadge}</td>
                    <td>${record.workstation || '-'}</td>
                    <td>${record.operator || '-'}</td>
                    <td>${record.shift || '-'}</td>
                    <td>${record.qualityStatus || '-'}</td>
                    <td>${this.formatDate(record.createTime)}</td>
                    <td>
                        <span class="remarks" title="${record.remarks || ''}">
                            ${this.truncateText(record.remarks, 20)}
                        </span>
                    </td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn btn-sm btn-info" onclick="app.showRecordDetail(${record.id})" title="Details">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="app.deleteProductionRecord(${record.id})" title="Delete">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');

        tbody.innerHTML = rows;
    }

    // Get record type badge
    getRecordTypeBadge(recordType) {
        const typeMap = {
            'PRODUCTION': '<span class="record-type-badge record-production">Production</span>',
            'REJECTION': '<span class="record-type-badge record-rejection">Rejection</span>',
            'REWORK': '<span class="record-type-badge record-rework">Rework</span>'
        };
        return typeMap[recordType] || '<span class="record-type-badge record-unknown">Unknown</span>';
    }

    // Update statistics
    updateStatistics() {
        const productionRecords = this.currentRecords.filter(r => r.recordType === 'PRODUCTION');
        const rejectionRecords = this.currentRecords.filter(r => r.recordType === 'REJECTION');
        
        // Today's records
        const today = new Date().toDateString();
        const todayProduction = productionRecords.filter(r => 
            new Date(r.createTime).toDateString() === today
        ).length;
        const todayRejection = rejectionRecords.filter(r => 
            new Date(r.createTime).toDateString() === today
        ).length;

        document.getElementById('productionCount').textContent = productionRecords.length;
        document.getElementById('rejectionCount').textContent = rejectionRecords.length;
        document.getElementById('todayProduction').textContent = todayProduction;
        document.getElementById('todayRejection').textContent = todayRejection;

        // Calculate efficiency rate
        const totalProduction = productionRecords.reduce((sum, r) => sum + (r.quantity || 0), 0);
        const totalRejection = rejectionRecords.reduce((sum, r) => sum + (r.quantity || 0), 0);
        const total = totalProduction + totalRejection;
        const efficiencyRate = total > 0 ? Math.round((totalProduction / total) * 100) : 0;
        
        document.getElementById('efficiencyRate').textContent = `${efficiencyRate}%`;
        document.getElementById('totalQuantity').textContent = totalProduction;
    }

    // Show add production modal
    showAddProductionModal() {
        document.getElementById('productionModal').classList.add('show');
    }

    // Hide production modal
    hideProductionModal() {
        document.getElementById('productionModal').classList.remove('show');
        document.getElementById('productionForm').reset();
    }

    // Add production record
    async addProductionRecord(formData) {
        try {
            const recordData = Object.fromEntries(formData);
            const params = new URLSearchParams({
                workOrderId: recordData.workOrderId,
                quantity: recordData.quantity,
                workstation: recordData.workstation,
                operator: recordData.operator,
                shift: recordData.shift
            });

            if (recordData.remarks) {
                params.append('remarks', recordData.remarks);
            }

            await this.apiCall(`/api/production-records/production?${params}`, {
                method: 'POST'
            });

            this.showToast('Production record added successfully', 'success');
            this.hideProductionModal();
            this.loadProductionRecords();
            this.loadOperators(); // Refresh operators list
            
        } catch (error) {
            console.error('Failed to add production record:', error);
        }
    }

    // Show add rejection modal
    showAddRejectionModal() {
        document.getElementById('rejectionModal').classList.add('show');
    }

    // Hide rejection modal
    hideRejectionModal() {
        document.getElementById('rejectionModal').classList.remove('show');
        document.getElementById('rejectionForm').reset();
    }

    // Add rejection record
    async addRejectionRecord(formData) {
        try {
            const recordData = Object.fromEntries(formData);
            const params = new URLSearchParams({
                workOrderId: recordData.workOrderId,
                quantity: recordData.quantity,
                workstation: recordData.workstation,
                operator: recordData.operator,
                shift: recordData.shift
            });

            if (recordData.qualityStatus) {
                params.append('qualityStatus', recordData.qualityStatus);
            }
            if (recordData.remarks) {
                params.append('remarks', recordData.remarks);
            }

            await this.apiCall(`/api/production-records/rejection?${params}`, {
                method: 'POST'
            });

            this.showToast('Rejection record added successfully', 'success');
            this.hideRejectionModal();
            this.loadProductionRecords();
            this.loadOperators(); // Refresh operators list
            
        } catch (error) {
            console.error('Failed to add rejection record:', error);
        }
    }

    // Delete production record
    async deleteProductionRecord(recordId) {
        if (!confirm('Are you sure you want to delete this production record? This action cannot be undone.')) {
            return;
        }

        try {
            await this.apiCall(`/api/production-records/${recordId}`, {
                method: 'DELETE'
            });

            this.showToast('Production record deleted successfully', 'success');
            this.selectedRecords.delete(recordId);
            this.loadProductionRecords();
            
        } catch (error) {
            console.error('Failed to delete production record:', error);
        }
    }

    // Refresh realtime status
    refreshRealtimeStatus() {
        // Simulate workstation status
        const workstations = ['工作站A1', '工作站B1', '工作站C1', '工作站D1'];
        const statuses = ['running', 'idle', 'maintenance', 'offline'];
        
        const statusContainer = document.getElementById('workstationStatus');
        if (statusContainer) {
            const statusHTML = workstations.map(station => {
                const status = statuses[Math.floor(Math.random() * statuses.length)];
                const statusClass = `status-${status}`;
                const statusText = {
                    'running': 'Running',
                    'idle': 'Idle', 
                    'maintenance': 'Maintenance',
                    'offline': 'Offline'
                }[status];
                
                return `
                    <div class="workstation-card ${statusClass}">
                        <div class="workstation-name">${station}</div>
                        <div class="workstation-status">${statusText}</div>
                        <div class="workstation-info">
                            <small>Last update: ${new Date().toLocaleTimeString('zh-CN')}</small>
                        </div>
                    </div>
                `;
            }).join('');
            
            statusContainer.innerHTML = statusHTML;
        }
    }

    // Utility functions
    formatDate(dateString) {
        if (!dateString) return '-';
        return new Date(dateString).toLocaleString('zh-CN');
    }

    truncateText(text, maxLength) {
        if (!text) return '-';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    }

    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast ${type}`;
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // Selection functions
    toggleRecordSelection(recordId) {
        if (this.selectedRecords.has(recordId)) {
            this.selectedRecords.delete(recordId);
        } else {
            this.selectedRecords.add(recordId);
        }
        this.renderProductionRecordsTable();
    }

    // Pagination functions
    updatePagination() {
        document.getElementById('pageStart').textContent = 
            this.currentRecords.length > 0 ? (this.currentPage - 1) * this.pageSize + 1 : 0;
        document.getElementById('pageEnd').textContent = 
            Math.min(this.currentPage * this.pageSize, this.totalItems);
        document.getElementById('totalItems').textContent = this.totalItems;

        document.getElementById('prevBtn').disabled = this.currentPage <= 1;
        document.getElementById('nextBtn').disabled = this.currentPage >= this.totalPages;

        this.generatePageNumbers();
    }

    generatePageNumbers() {
        const pageNumbers = document.getElementById('pageNumbers');
        let html = '';

        const maxVisiblePages = 5;
        let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);

        for (let i = startPage; i <= endPage; i++) {
            html += `
                <button class="btn btn-sm ${i === this.currentPage ? 'btn-primary' : 'btn-secondary'}" 
                        onclick="app.goToPage(${i})">${i}</button>
            `;
        }

        pageNumbers.innerHTML = html;
    }

    goToPage(page) {
        if (page >= 1 && page <= this.totalPages) {
            this.currentPage = page;
            this.renderProductionRecordsTable();
            this.updatePagination();
        }
    }

    previousPage() {
        if (this.currentPage > 1) {
            this.goToPage(this.currentPage - 1);
        }
    }

    nextPage() {
        if (this.currentPage < this.totalPages) {
            this.goToPage(this.currentPage + 1);
        }
    }
}

// Global functions
function showAddProductionModal() {
    window.app.showAddProductionModal();
}

function showAddRejectionModal() {
    window.app.showAddRejectionModal();
}

function hideProductionModal() {
    window.app.hideProductionModal();
}

function hideRejectionModal() {
    window.app.hideRejectionModal();
}

function refreshRealtimeStatus() {
    window.app.refreshRealtimeStatus();
}

function searchRecords() {
    if (window.app) {
        window.app.showToast('Search function under development...', 'info');
    }
}

function clearFilters() {
    if (window.app) {
        window.app.showToast('Clear filters function under development...', 'info');
    }
}

function exportRecords() {
    if (window.app) {
        window.app.showToast('Export function under development...', 'info');
    }
}

function setQuickTime(days) {
    const endTime = new Date();
    const startTime = new Date();
    startTime.setDate(startTime.getDate() - days);
    
    // Adjust for timezone
    endTime.setMinutes(endTime.getMinutes() - endTime.getTimezoneOffset());
    startTime.setMinutes(startTime.getMinutes() - startTime.getTimezoneOffset());
    
    document.querySelector('input[name="startTime"]').value = startTime.toISOString().slice(0, 16);
    document.querySelector('input[name="endTime"]').value = endTime.toISOString().slice(0, 16);
}

function previousPage() {
    window.app.previousPage();
}

function nextPage() {
    window.app.nextPage();
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    window.app = new ProductionRecordsApp();
    
    // Initialize realtime status
    if (window.app) {
        window.app.refreshRealtimeStatus();
    }
});